import {
  BadGatewayException,
  Controller,
  Get,
  Param,
  Query,
  Redirect,
  Render,
  Req,
  Res,
} from '@nestjs/common';
import { AppService } from './app.service';
import { Response, Request } from 'express';
import { Article } from './entity/article.entity';
import * as dayjs from 'dayjs';
import { LessThan } from 'typeorm';
import { SitemapService } from './service/sitemap.service';
@Controller()
export class AppController {
  constructor(
    private readonly appService: AppService,
    private readonly sitemapService: SitemapService,
  ) {}

  @Get('*[/]')
  removeTrailingSlash(@Res() res: Response, @Req() req: Request) {
    let newUrl = req.originalUrl.replace(/\/$/, '');
    res.redirect(301, newUrl);
  }

  @Get()
  @Render('index')
  async index(
    @Query('pageNum') pageNum: number = 1,
    @Query('pageSize') pageSize: number = 10,
  ) {
    let now = dayjs().unix();

    let articleList = await Article.find({
      where: {
        startTime: LessThan(now),
      },
      skip: (pageNum - 1) * pageSize,
      take: 10,
      order: {
        createTime: 'DESC',
      },
    });

    let list = [];
    articleList.map((item) => {
      let obj = {
        ...item,
        createTime: dayjs(item.createTime).format('YYYY-MM-DD'),
      };
      list.push(obj);
    });

    return {
      articleList: list,
    };
  }

  @Get('category/latest-news')
  @Render('category/latest-news')
  async latestNews(
    @Query('pageNum') pageNum: number = 1,
    @Query('pageSize') pageSize: number = 10,
  ) {
    let now = dayjs().unix();

    let articleList = await Article.find({
      where: {
        startTime: LessThan(now),
      },
      take: 10,
      order: {
        createTime: 'DESC',
      },
    });

    let list = [];
    articleList.map((item) => {
      let obj = {
        ...item,
        createTime: dayjs(item.createTime).format('YYYY-MM-DD'),
      };
      list.push(obj);
    });

    return {
      articleList: list,
    };
  }

  @Get('category/industry-trends')
  @Render('category/industry-trends')
  async industryTreneds(
    @Query('pageNum') pageNum: number = 1,
    @Query('pageSize') pageSize: number = 10,
  ) {
    let now = dayjs().unix();

    let articleList = await Article.find({
      where: {
        startTime: LessThan(now),
      },
      skip: (pageNum - 1) * pageSize,
      take: 10,
      order: {
        createTime: 'DESC',
      },
    });

    let list = [];
    articleList.map((item) => {
      let obj = {
        ...item,
        createTime: dayjs(item.createTime).format('YYYY-MM-DD'),
      };
      list.push(obj);
    });

    return {
      articleList: list,
    };
  }

  @Get('category/faq')
  @Render('category/faq')
  async faq(
    @Query('pageNum') pageNum: number = 1,
    @Query('pageSize') pageSize: number = 10,
  ) {
    let now = dayjs().unix();

    let articleList = await Article.find({
      where: {
        startTime: LessThan(now),
      },
      skip: (pageNum - 1) * pageSize,
      take: 10,
      order: {
        createTime: 'DESC',
      },
    });

    let list = [];
    articleList.map((item) => {
      let obj = {
        ...item,
        createTime: dayjs(item.createTime).format('YYYY-MM-DD'),
      };
      list.push(obj);
    });

    return {
      articleList: list,
    };
  }

  @Get('1688-purchasing-agent')
  @Render('1688-purchasing-agent')
  async purchasingAgent() {
    return;
  }

  @Get('about-us')
  @Render('about-us')
  async aboutUs() {
    return;
  }

  @Get('china-wholesale-sunglasses-complete-guide')
  @Render('china-wholesale-sunglasses-complete-guide')
  async chinaWholesaleSunglassesCompleteGuide() {
    return;
  }

  @Get('contact-us')
  @Render('contact-us')
  async contactUs() {
    return;
  }

  @Get('how-to-buy-wholesale-in-china')
  @Render('how-to-buy-wholesale-in-china')
  async howToBuyWholesaleInChina() {
    return;
  }

  @Get('import-top-25-cheap-products-from-china-to-help-you-make-big-money')
  @Render('import-top-25-cheap-products-from-china-to-help-you-make-big-money')
  async howToBuyWholesaleInChina1() {
    return;
  }

  @Get('yiwu-market-agent')
  @Render('yiwu-market-agent')
  async yiwuMarketAgent() {
    return;
  }

  @Get(':name')
  async root(@Res() res: Response, @Param('name') name: string) {
    let article = await Article.findOne({ where: { seoKeywords: name } });
    if (article) {
      let now = dayjs().unix();

      if (article.startTime > now) {
        throw new BadGatewayException('文章未发布');
      }

      // 查询文章
      let articleList = await Article.find({
        where: {
          startTime: LessThan(now),
        },
        skip: 0,
        take: 10,
      });

      let list = [];
      articleList.map((item) => {
        let obj = {
          ...item,
          createTime: dayjs(item.createTime).format('YYYY-MM-DD'),
        };

        list.push(obj);
      });

      // last
      let lastArticle = await Article.findOne({
        where: { id: article.id - 1 },
      });
      // next
      let nextArticle = await Article.findOne({
        where: { id: article.id + 1 },
      });

      return res.render('article', {
        article: {
          ...article,
          createTime: dayjs(article.createTime).format('YYYY-MM-DD'),
        },
        lastArticle,
        nextArticle,
        list,
      });
    } else {
      throw new BadGatewayException('文章不存在');
    }
  }
}
